﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Netduino4Fun.DesktopAssistant.Windows.Netduino
{
	public class Netduino : INotifyPropertyChanged
	{

		#region INotifyPropertyChanged
		public event PropertyChangedEventHandler PropertyChanged;

		private void RaisePropertyChanged(string propertyName)
		{
			if (PropertyChanged == null) return;
			PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}
		#endregion

		private static Netduino _instance;

		public static Netduino Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new Netduino();
				}
				return _instance;
			}
		}

		public enum EnumConnectionState
		{
			Waiting,
			Connected,
			Error
		}

		private EnumConnectionState _connectionState;
		public EnumConnectionState ConnectionState
		{
			get { return _connectionState; }
			set
			{
				_connectionState = value;
				RaisePropertyChanged("ConnectionState");
			}
		}

		Connection connection;

		public void ConnectSerial()
		{
			ConnectionState = EnumConnectionState.Waiting;
			connection = new SerialConnection();
			connection.LineReceived += new LineReceivedEventHandler(connection_LineReceived);
			try
			{
				connection.Open();
				connection.WriteLine("Hello Netduino !");
				connection.WriteLine(DateTime.Now.Ticks.ToString());
			}
			catch (Exception)
			{
				ConnectionState = EnumConnectionState.Error;
				return;
			}
			ConnectionState = EnumConnectionState.Connected;
		}

		void connection_LineReceived(string line)
		{
			if (LineReceived != null)
				LineReceived(line);
		}

		public void ChangeColor(int red, int green, int blue)
		{
			string request = string.Format("ChangeColor {0} {1} {2}", red, green, blue);
			connection.WriteLine(request);
		}

		public event LineReceivedEventHandler LineReceived;

	}
}
